import * as crypto from 'crypto'

function sortedQueryString(obj) {
  const sortedKeys = Object.keys(obj).sort()
  return sortedKeys.map((key) => `${key}=${obj[key]}`).join('&')
}

export default (key) => {
  const keyString = `&key=${key}`

  return {
    sign(obj) {
      const string = sortedQueryString(obj) + keyString;

      const md5sum = crypto.createHash('md5')
      md5sum.update(new Buffer(string))
      return md5sum.digest('hex').toUpperCase()
    },
    secondSign(obj) {
      const string = `${sortedQueryString(obj)}&${this.sign(obj)}`
      const md5sum = crypto.createHash('md5')
      md5sum.update(new Buffer(string))
      return md5sum.digest('hex').toUpperCase()
    },
    verify(obj) {
      const sign = obj.sign
      delete obj.sign
      return this.sign(obj) === sign
    }
  }
}
